﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net;
using System.IO;
using System.Xml.Xsl;
using System.Text;
using System.Xml;

namespace Ashlen.Portal.Services.Handlers
{
    /// <summary>
    /// FormHandler is a dynamic form generator.
    /// It will accept an XML and XSLT and return the result of the conversion.
    /// </summary>
    public class FormHandler : IHttpHandler
    {
        #region variables
        private string _xml = string.Empty;
        private string _xsl = string.Empty;
        private string _response_content_type = string.Empty;
        private string _usage = @"
About
-----
This handler accepts XML and XSL urls and a return content type. It then transforms 
the XML using the supplied XSL and returns the output using the supplied content type.
";
        #endregion

        public void ProcessRequest(HttpContext context)
        {
            try
            {
                _xml = context.Request.Params["xml"] ?? string.Empty;
                _xsl = context.Request.Params["xsl"] ?? string.Empty;
                _response_content_type = context.Request.Params["ctype"] ?? string.Empty;

                if (_xml == string.Empty || _xsl == string.Empty || _response_content_type == string.Empty)
                {
                    context.Response.ContentType = "text/plain";
                    context.Response.Write(string.Format(_usage + "{0}XML, XSL and CType are required parameters.{0}XML = Url of the XML file{0}XSL = Url of the XSL file{0}" +
                    "CType = The content type of the Response object", Environment.NewLine));
                    return;
                }
                context.Response.ContentType = "application/x-javascript";
                //context.Server.HtmlEncode
                string html = Helper.Instance.Transform(Helper.Instance.Download(_xsl), Helper.Instance.Download(_xml)).Replace('\n', ' ');
                //html += context.Server.HtmlEncode(html);
                var lines = html.Split('\r');
                string variableName = "var_" + System.Guid.NewGuid().ToString().Replace("-", "_");
                string variable = string.Format("var {0} = '';", variableName) + Environment.NewLine;
                foreach (var line in lines)
                {
                    variable += string.Format("{0} += '", variableName) + context.Server.HtmlEncode(line).Replace("'", "") + "';" + Environment.NewLine;
                }
              //  string output = "<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js' type='text/javascript'></script>" + Environment.NewLine;
              //  string output = "document.write(\"" + "<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js' type='text/javascript'></script>" + "\");" + Environment.NewLine;
                string output = "";
                string guid = System.Guid.NewGuid().ToString();
                // output += "document.write(\"" +  "<script type=\"text/javascript\">" + "\");" + Environment.NewLine;
                output += "document.write('<div id=\"" + guid + "\"></div>');" + Environment.NewLine;
                output += "$(document).ready(function() {" + Environment.NewLine;
                output += variable + Environment.NewLine;
                output += "$(\"#" + guid + string.Format("\").html($('<div/>').html({0}).text());", variableName) + Environment.NewLine;
                output += "});" + Environment.NewLine;

                context.Response.Write(output);
            }
            catch (Exception ex)
            {
                context.Response.ContentType = "text/plain";
                context.Response.Write(ex.ToString());
                return;
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}